--[[-------------------------------------------------------------------------
  Copyright (c) 2006-2007, Trond A Ekseth
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Atropine nor the names of its contributors
        may be used to endorse or promote products derived from this
        software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------]]

local buyDelay = CreateFrame"Frame"
local B, Q, L = {}, {}
local addon = DongleStub"Dongle-1.0":New"Atropine"
local print = function(...) addon:Print(...) end
local printf = function(...) addon:PrintF(...) end
local GetID = function(item)
	if type(item) == "number" then return item
	elseif type(item) == "string" then
		local _, _, id = string.find(item, "item:(%d+):")
		if id then return tonumber(id) end
	end
end
local function sortedpairs(t,comparator)
	local sortedKeys = {}
	table.foreach(t, function(k,v) table.insert(sortedKeys,k) end)
	table.sort(sortedKeys,comparator)
	local i = 0
	local function _f(_s,_v)
		i = i + 1
		local k = sortedKeys[i]
		if (k) then
			return k,t[k]
		end
	end
	return _f
end
local CashString = function(money)
	if(not money) then return end

	local str, sep = "", " "
	local cS, cC, cG = "|cffC0C0C0", "|cffCC9900", "|cffFFFF66"

	if(money == 0) then return cC..money..sep..COPPER end

	local gold = math.floor(money / (COPPER_PER_SILVER * SILVER_PER_GOLD))
	local silver = math.floor((money - (gold * COPPER_PER_SILVER * SILVER_PER_GOLD)) / COPPER_PER_SILVER)
	local copper = math.fmod(money, COPPER_PER_SILVER)

	if(gold > 0) then str = cG..gold..sep..GOLD end
	if(silver > 0) then str = str..(str ~= "" and sep or "")..cS..silver..sep..SILVER end
	if(copper > 0) then str = str..(str ~= "" and sep or "")..cC..copper..sep..COPPER end

	return str
end
local pid = {
--	[0] = "Flash Powder",
	["1"] = "Anesthetic Poison",
	["2"] = "Crippling Poison",
	["3"] = "Deadly Poison",
	["4"] = "Instant Poison",
	["5"] = "Mind-numbing Poison",
	["6"] = "Wound Poison",
}
-- We could fetch the name of the first rank only, and generate a rank list from that. The
-- problem however is that not everyone trains the first rank. This list is compiled by
-- doing it however. The format is - <itemid>:<pid>:<rank>.
-- 			  AP1           CP2         DP7           IP7            MP3        WP5          CP1        DP6           IP6          MP2        WP4          DP5           IP5          MP1        WP3          DP4         IP4          WP2          DP3        IP3          WP1          DP2         IP2          DP1         IP1
local poisons = " 21835:1:1 3776:2:2 22054:3:7 21927:4:7 9186:5:3 22055:6:5 3775:2:1 22053:3:6 8928:4:6 6951:5:2 10922:6:4 20844:3:5 8927:4:5 5237:5:1 10921:6:3 8985:3:4 8926:4:4 10920:6:2 8984:3:3 6950:4:3 10918:6:1 2893:3:2 6949:4:2 2892:3:1 6947:4:1"
local dbver = 3
local defaults = {
	char = {
		db = dbver,
		poisons = {},
		auto = {},
	}
}
addon.locale = {}

function addon:Initialize()
	L = AtropineLocale

	self.db = self:InitializeDB("AtropineDB", defaults)
	self.char = self.db.char

	self.Initialize = nil
end

function addon:Enable()
	local GetSpellTexture, type = GetSpellTexture, BOOKTYPE_SPELL
	local i, texture = 1, GetSpellTexture(1, type)

	while(texture ~= "Interface\\Icons\\Trade_BrewPoison" and texture) do
		i= i + 1
		texture = GetSpellTexture(i, type)
	end
	
	local class = select(2, UnitClass"player")
	if(class ~= "ROGUE") then
		DisableAddOn("Atropine")
		return print(L["Disabled"])
	elseif(texture) then
		L.Poisons = GetSpellName(i, type)
	elseif(not texture) then
		return -- This shouldn't happen at all if you are a rogue with poisons.
	end

	self.frame = self:createFrame("AtropineFrame", true)
	self.frame:SetPoint("TOP", MerchantFrame, "BOTTOM", 15, 0)

	local time = 0
	buyDelay:Hide()
	buyDelay:SetScript("OnUpdate", function(self, a1)
		time = time + a1
	
		if(time > 2) then
			if(addon.frame:IsShown()) then addon:buy(true) end
			self:Hide()
			time = 0
		end
	end)


	self:RegisterEvent("MERCHANT_SHOW", "merchantShow")
	self:RegisterEvent("MERCHANT_CLOSED", "merchantClosed")
	self:RegisterEvent("PLAYER_LEVEL_UP", "playerLevelUp")
	self:registerEvents()

	if(self.char.cache ~= UnitLevel"player" and dbver == self.char.db) then
		self:registerEvents()
	else
		self:updateDB()
	end

	self.Enable = nil
end

function addon:updateDB()
	-- Idiot check...
	if(self.char.db > dbver) then self.char.db = dbver end

	while(self.char.db ~= dbver) do
		if(self.char.db < 3) then
			self.char.poisons = {}
			self.char.db = 3

			print(L["DB Format"])
		end
	end

	local b, cache = 1, self.char.poisons
	for p, v in sortedpairs(cache) do
		self.frame[b] = self.button:new(p, v.texture, b)
		b = b + 1
	end
end

function addon:registerEvents()
	self:RegisterEvent("TRADE_SKILL_UPDATE", "createCache")
end

function addon:IsPoisonVendor()
	for m=1,GetMerchantNumItems() do
		local link = GetMerchantItemLink(m)
		if(GetID(link) == 5140) then return true end
	end
	return false
end

function addon:createCache()
	self:UnregisterEvent"TRADE_SKILL_UPDATE"
	if(not GetTradeSkillLine() == L["Poisons"]) then return end
	
	local cache = {}
	local matched = {}

	self.char.poisons = cache
	for i=1, GetNumTradeSkills() do
		local link = GetTradeSkillItemLink(i)
		local itemid = GetID(link)
		
		if(itemid) then
			local type, rank = poisons:match("%s"..itemid..":(%d):(%d)")
			type = pid[type]

			if(type and not matched[type]) then
				local name = GetTradeSkillInfo(i)
				local texture = GetTradeSkillIcon(i)
				cache[type] = {
					name = name,
					ts = i,
					link = link,
					itemid = itemid,
					rank = rank,
					texture = texture,
				}
				local mats = {}
				cache[type].mats = mats
				for j=1, GetTradeSkillNumReagents(i) do
					local rid = GetID(GetTradeSkillReagentItemLink(i, j))
					local q = select(3, GetTradeSkillReagentInfo(i, j))

					mats[rid] = q
				end
				
				matched[type] = true
			end
		end
	end
	-- Inject flashpowder for now:
	local name, link, _, _, _, _, _, _, _, texture = GetItemInfo(5140)
	if(name) then
		cache["Flash Powder"] = {
			name = name,
			link = link,
			itemid = GetID(link),
			mats = {[5140] = 1},
			texture = texture,
		}
	end
	
	local i = 1
	for p, v in sortedpairs(cache) do
		self.frame[i] = self.button:new(p, v.texture, i)
		i = i + 1
	end

	self.char.cache = UnitLevel"player"
end

function addon:merchantShow()
	if(GetMerchantNumItems() == 0) then
		self:RegisterEvent("MERCHANT_UPDATE", "merchantShow")
	elseif(self:IsPoisonVendor()) then
		self.frame:Show()
		self:UnregisterEvent"MERCHANT_UPDATE"

		if(not IsShiftKeyDown() and self.char.cache == UnitLevel"player") then
			for k,v in pairs(self.char.auto) do
				if(v.e) then
					self:add(k, v.q, true)
				end
			end
			buyDelay:Show()
		end
	end
end

function addon:merchantClosed()
	if(self.frame:IsShown()) then self.frame:Hide() end
	for k in pairs(B) do B[k] = nil end
	self:UnregisterEvent"MERCHANT_UPDATE"
end

function addon:playerLevelUp(event, level)
	self:registerEvents()
end

function addon:buy(refill)
	for r, c in pairs(B) do
		for m=1, GetMerchantNumItems() do
			local name, _, price, num = GetMerchantItemInfo(m)
			local link = GetMerchantItemLink(m)
			if(GetID(link) == r) then
				local t = ((r ~= 5140 and refill and c - GetItemCount(r)) or c)/num
				while(t > 0) do
					local b = math.min(t, GetMerchantItemMaxStack(m))
					BuyMerchantItem(m, b)
					t = t - b
				end
				B[r] = nil
			end
		end
	end
end

function addon:getFullName(poison)
	local sc = self.char.poisons[poison]
	if(sc) then
		return sc.name
	else
		return poison
	end
end

function addon.decimalToRoman(d)
	local r = ""
	if(d <= 0) then return end
	while(d ~= 0) do
		if(d >= 10) then
			d = d - 10;r = r.."X"
		elseif(d == 9) then
			d = d - 9;r = r.."IX"
		elseif(d >= 5) then
			d = d - 5;r = r.."V"
		elseif(d == 4) then
			d = d - 4;r = r.."IV"
		elseif(d >= 1) then
			d = d - 1;r = r.."I"
		end
	end
	return r
end

function addon:getCost(poison, amount, refill)
	poison = self.char.poisons[poison]
	amount = (refill and amount - GetItemCount(poison.itemid)) or amount
	local total = 0

	if(amount <= 0) then return CashString(total) end

	for r, q in pairs(poison.mats) do
		for m=1, GetMerchantNumItems() do
			local _, _, price, num = GetMerchantItemInfo(m)
			local link = GetID(GetMerchantItemLink(m))

			if(link == r) then
				total = total + ((q/num)*amount)*price
			end
		end
	end

	return CashString(total)
end

function addon:create()
	local key, amount = next(Q)

	if(key and amount > 0) then
		local ptbl = self.char.poisons[key]
		if(ptbl) then
			self:PrintF(L["Create"], amount, ptbl.link)
			DoTradeSkill(ptbl.ts, amount)
		end
		Q[key] = nil
	end
end

function addon:add(poison, amount, refill)
	local ptbl = self.char.poisons[poison]
	if(not ptbl) then return end
	amount = (refill and amount - GetItemCount(ptbl.itemid)) or amount
	if(amount > 0) then
		local link = ptbl.link
		printf(L["Buying"], amount, link)

		if(poison ~= "Flash Powder") then Q[poison] = Q[poison] or 0 + amount end

		for r, q in pairs(ptbl.mats) do
			q = amount * q
			B[r] = (B[r] or 0) + q
		end
	end
end

function addon:getRefill(poison)
	local v = self.char.auto[poison]
	if(not v) then return false end
	return v.e, v.q
end

function addon:updateRefillV(poison, q)
	if(not self.char.auto[poison]) then self.char.auto[poison] = {} end
	self.char.auto[poison].q = q
end

function addon:updateRefillS(poison, update)
	if(not self.char.auto[poison]) then self.char.auto[poison] = {q = 0} end
	self.char.auto[poison].e = update
end

_G["Atropine"] = addon
